// 中间件鉴权
module.exports = async (req, res, next) => {
  var db = require("../db");
  var jwt = require("jsonwebtoken");
  console.log(req.headers);
  const token = String(req.headers.authorization || " ")
    .split(" ")
    .pop();
  console.log(token);
  if (!token) {
    res.send({
      code: -1011,
      msg: "token不存在,请重新登录",
    });
  }
  try {
    var decoded = jwt.verify(token, "secret");
    console.log(decoded);
    const sql = "select * from admin where id = ?";
    const { results } = await db.query(sql, decoded.id);
    req.user = results[0];
    next();
  } catch (error) {
    res.send({
      code: -1110,
      msg: "token已失效",
    });
  }
};
